import 'package:base_lib/common/base/base_theme_state.dart';
import 'package:base_lib/common/index.dart';
import 'package:base_lib/config.dart';
import 'package:base_lib/index.dart';
import 'package:base_lib/router/routers.dart';
import 'package:base_lib/theme/theme_global.dart';
import 'package:doctor_order_lib/prescription/view_rp_img_page.dart';
import 'package:doctor_order_lib/repository/order_http.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../component.dart';
import 'entity/prescription_order_list_entity.dart' as OrderListBean;
import 'entity/rp_detail_entity.dart' as RpDetailBean;
import 'entity/prescription_order_info_entity.dart' as OrderInfoBean;

///订单详情
class PrescriptionOrderDetailPage extends StatefulWidget {
  final Parameters parameters;

  PrescriptionOrderDetailPage(this.parameters);

  @override
  State<StatefulWidget> createState() {
    return _State();
  }
}

class _State extends BaseThemeState<PrescriptionOrderDetailPage> {
  var tsWhite = TextStyle(color: Colors.white, fontSize: 18);
  var tsBlackBig =
      TextStyle(color: Colors.black, fontSize: 16, fontWeight: FontWeight.bold);
  var tsBlack = TextStyle(color: Colors.black, fontSize: 14);

  OrderListBean.Datas item;

  RpDetailBean.Data rpDetailData;

  OrderInfoBean.Data orderInfoData;

  void doRefresh() {
    setState(() {});
  }

  @override
  void initState() {
    super.initState();
    item = widget.parameters.getObj('item');
    getRp();
  }

  void getRp() async {
    var result = await DoctorOrderHttp.getOrderRpDetail(item.rpID);
    if (result.isSuccess) {
      rpDetailData = result.data;
      getOrder();
    } else {
      ToastUtil.error(result.error.msg);
      Routers.pop(context);
    }
    DoctorOrderHttp.getOrderMedicineOrRp(item.keyID);
  }

  void getOrder() async {
    var result = await DoctorOrderHttp.getOrderMedicineOrRp(item.keyID);
    if (result.isSuccess) {
      orderInfoData = result.data;
      doRefresh();
      getMedicineInfo();
      getMedicineImgs();
    } else {
      ToastUtil.error(result.error.msg);
      Routers.pop(context);
    }
  }

  void getMedicineInfo() async {
    var ids = orderInfoData.details.map((e) => e.medicineID).toList();
    var result = await DoctorOrderHttp.getOrderMedicineInfoDetailsByIds(ids);
    if (result.isSuccess) {
      orderInfoData.details.forEach((detail) {
        result.data.forEach((medicine) {
          if (detail.medicineID == medicine.medicineID) {
            detail.productBrand = medicine.productBrand;
            detail.otcType = medicine.otcType;
            detail.productSpec = medicine.productSpec;
            detail.medicineName = medicine.medicineName;
          }
        });
      });
      doRefresh();
    }
  }

  void getMedicineImgs() async {
    var ids = orderInfoData.details.map((e) => e.medicineID).toList();
    var result = await DoctorOrderHttp.getOrderMedicineImages(ids);
    if (result.isSuccess) {
      List resImagesData = result.data['data'];
      resImagesData.forEach((item) {
        orderInfoData.details.forEach((its) {
          if (item.medicineID == its.medicineID) {
            its.imgUrl = item['imgUrl'].toString();
            if (its.imgUrl.substring(its.imgUrl.length - 3) == "jpg" ||
                its.imgUrl.substring(its.imgUrl.length - 3) == "png" ||
                its.imgUrl.substring(its.imgUrl.length - 4) == "jpeg") {
              its.imgUrl = "";
            }
          }
        });
      });

      doRefresh();
    }
  }

  @override
  Widget buildChild(BuildContext context, MTheme theme) {
    return Scaffold(
      backgroundColor: theme.themeColor.themeBgColor,
      appBar: AppBar(
        leading: BackButton(
          onPressed: () {
            Routers.pop(context);
          },
        ),
        title: Text('订单详情'),
        centerTitle: true,
      ),
      body: orderInfoData == null
          ? buildLoadingIndicator()
          : Container(
              child: SingleChildScrollView(
                child: Column(
                  children: [
                    Container(
                      width: double.infinity,
                      padding: EdgeInsets.only(top: 20, bottom: 20),
                      color: theme.themeColor.themeColor,
                      child: Column(
                        children: [
                          orderInfoData.orderStatusID == 10
                              ? Padding(
                                  padding: const EdgeInsets.all(8.0),
                                  child: Text(
                                    '${orderInfoData.deliveryStatusName}',
                                    style: tsWhite,
                                  ),
                                )
                              : SizedBox(),
                          orderInfoData.orderStatusID == 0 &&
                                  orderInfoData.payTypeID == 2
                              ? Padding(
                                  padding: const EdgeInsets.all(8.0),
                                  child: Text(
                                    '${orderInfoData.orderStatusName} (${orderInfoData.payTypeName})',
                                    style: tsWhite,
                                  ),
                                )
                              : SizedBox(),
                          orderInfoData.orderStatusID == 0 &&
                                  orderInfoData.payTypeID != 2
                              ? Padding(
                                  padding: const EdgeInsets.all(8.0),
                                  child: Text(
                                    '${orderInfoData.orderStatusName}',
                                    style: tsWhite,
                                  ),
                                )
                              : SizedBox(),
                          10.vGapDp,
                          orderInfoData.orderStatusID == 0
                              ? Padding(
                                  padding: const EdgeInsets.all(8.0),
                                  child: Text(
                                    '需付款： ￥${Config.formatMoney(orderInfoData.orderPrice)}',
                                    style: tsWhite,
                                  ),
                                )
                              : SizedBox(),
                        ],
                      ),
                    ),
                    10.vGapDp,
                    _buildPrescription(theme),
                    10.vGapDp,
                    _buildDelivery(theme),
                    10.vGapDp,
                    _buildMoney(theme),
                    50.vGapDp,
                  ],
                ),
              ),
            ),
    );
  }

  _buildPrescription(MTheme theme) {
    List<Widget> ws = (!(rpDetailData.keyID?.isNotEmpty == true) ||
            rpDetailData.rpTypeID == 0)
        ? _buildWestPrescription(theme)
        : _buildChinesePrescription(theme);

    return Container(
      padding: EdgeInsets.all(10),
      decoration: BoxDecoration(
          color: Colors.white, borderRadius: BorderRadius.circular(5)),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: []
          ..addAll(ws)
          ..addAll([
            10.vGapDp,
            Row(
              children: [
                Text(
                  '用药人信息',
                  style: tsBlackBig,
                ),
                Spacer(),
                Text(
                  '${rpDetailData.patientInfo.patientName}',
                  style: tsBlack,
                ),
              ],
            ),
            10.vGapDp,
            rpDetailData.rpImgFileUrl?.isNotEmpty == true
                ? GestureDetector(
                    onTap: () {
                      Navigator.push(context,
                          MaterialPageRoute(builder: (context) {
                        return ViewRpImgPage(rpDetailData.rpImgFileUrl);
                      }));
                    },
                    child: SizedBox(
                      width: 70,
                      height: 100,
                      child: Stack(
                        children: [
                          FadeInImage.assetNetwork(
                              placeholder:
                                  'packages/${DoctorOrderComponent.AssetPackageName}/images/rpFileStampFileUrl.png',
                              image: rpDetailData.rpImgFileUrl),
                          Positioned(
                            bottom: 0,
                            left: 0,
                            child: Container(
                              padding: EdgeInsets.symmetric(vertical: 2),
                              alignment: Alignment.center,
                              width: 70,
                              color: Colors.grey[400],
                              child: Text(
                                '处方笺',
                                style: tsWhite.copyWith(fontSize: 10),
                              ),
                            ),
                          )
                        ],
                      ),
                    ),
                  )
                : SizedBox(),
            rpDetailData.rpImgFileUrl?.isNotEmpty == true
                ? 10.vGapDp
                : SizedBox()
          ]),
      ),
    );
  }

  ///西药
  List<Widget> _buildWestPrescription(MTheme theme) {
    var medicinesWidgets = <Widget>[];
    orderInfoData.details.forEach((medicine) {
      medicinesWidgets.add(Container(
        padding: EdgeInsets.symmetric(vertical: 5),
        child: Row(
          children: [
            SizedBox(
              width: 90,
              child: Stack(
                children: [
                  FadeInImage.assetNetwork(
                      placeholder:
                          'packages/${DoctorOrderComponent.AssetPackageName}/images/medicine.png',
                      image: medicine.imgUrl ?? ''),
                  Positioned(
                    top: 0,
                    right: 0,
                    child: medicine.otcType == 0
                        ? Container(
                            padding: EdgeInsets.symmetric(
                                vertical: 2, horizontal: 3),
                            decoration: BoxDecoration(
                                color: Colors.red,
                                borderRadius: BorderRadius.circular(15)),
                            child: Text('处方药',
                                style: tsWhite.copyWith(fontSize: 10)),
                          )
                        : SizedBox(),
                  ),
                ],
              ),
            ),
            10.hGapDp,
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                      '${medicine.productFactory}     ${medicine.medicineName}',
                      style: tsBlack),
                  5.vGapDp,
                  Text('规格：${medicine.productSpec}',
                      style: tsBlack.copyWith(color: Colors.grey)),
                  5.vGapDp,
                  Row(
                    children: [
                      Text('¥：${Config.formatMoney(medicine.priceItem)}',
                          style: tsBlack.copyWith(color: Colors.red)),
                      Spacer(),
                      Text('x ${medicine.itemCount}', style: tsBlack),
                    ],
                  )
                ],
              ),
            )
          ],
        ),
      ));
      
      medicinesWidgets.add(DottedLine(color: Colors.grey[200],dashWidth: 2));
    });

    return medicinesWidgets;
  }

  ///中药
  List<Widget> _buildChinesePrescription(MTheme theme) {
    var medicinesStr = '';
    rpDetailData.medicines.forEach((medicine) {
      medicinesStr +=
          '${medicine.medicineName} ${medicine.medicineAmount} ${medicine.takeDirection}\n';
    });

    return [
      5.vGapDp,
      Text(
        '药品处方',
        style: tsBlackBig,
      ),
      5.vGapDp,
      Text(
        medicinesStr,
        style: tsBlack,
      ),
      5.vGapDp,
      Text(
        '${rpDetailData.medicineFormID == 10 ? '饮片' : rpDetailData.medicineFormID == 11 ? '颗粒剂' : ''}',
        style: tsBlack,
      ),
      10.vGapDp,
      DottedLine(color: Colors.grey[200], dashWidth: 2),
      10.vGapDp,
      Text(
        '用法用量',
        style: tsBlackBig,
      ),
      5.vGapDp,
      Text(
        '${rpDetailData.chineseMedicine.direction}，共${rpDetailData.totalDoses}剂，每日${rpDetailData.chineseMedicine.frequence}剂，每剂分${rpDetailData.chineseMedicine.everyDose}次服用。',
        style: tsBlack,
      ),
      10.vGapDp,
      DottedLine(color: Colors.grey[200], dashWidth: 1),
      10.vGapDp,
      Text(
        '医嘱提醒',
        style: tsBlackBig,
      ),
      5.vGapDp,
      Container(
        height: 70,
        width: double.infinity,
        padding: EdgeInsets.all(10),
        decoration: BoxDecoration(
            color: theme.themeColor.themeBgColor,
            borderRadius: BorderRadius.circular(10)),
        child: Text(
          '${rpDetailData.enjoin != null && rpDetailData.enjoin.isNotEmpty ? rpDetailData.enjoin : '无'}',
          style: tsBlack,
        ),
      ),
      10.vGapDp,
      DottedLine(color: Colors.grey[200], dashWidth: 1),
    ];
  }

  ///配送方式
  _buildDelivery(MTheme theme) {
    return Container(
      padding: EdgeInsets.all(10),
      decoration: BoxDecoration(
          color: Colors.white, borderRadius: BorderRadius.circular(5)),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          5.vGapDp,
          Row(
            children: [
              Text('配送方式', style: tsBlackBig),
              Spacer(),
              Text('${orderInfoData.deliveryTypeName}', style: tsBlack),
            ],
          ),
          5.vGapDp,
          1.gapV(Colors.grey[200]),
          15.vGapDp,
          Row(
            children: [
              Text('${orderInfoData.receiverName}', style: tsBlackBig),
              10.hGapDp,
              Text('${orderInfoData.receiverPhone}', style: tsBlack),
              Spacer(),
            ],
          ),
          5.vGapDp,
          Text(
              '${orderInfoData.province} ${orderInfoData.city} ${orderInfoData.area} ${orderInfoData.address}',
              style: tsBlack),
          15.vGapDp,
          1.gapV(Colors.grey[200]),
          15.vGapDp,
          Text('备注', style: tsBlackBig),
          5.vGapDp,
          Text('${orderInfoData.remarks.isEmpty ? '无' : orderInfoData.remarks}',
              style: tsBlack),
          10.vGapDp,
        ],
      ),
    );
  }

  ///金额
  _buildMoney(MTheme theme) {
    return Container(
      padding: EdgeInsets.all(10),
      decoration: BoxDecoration(
          color: Colors.white, borderRadius: BorderRadius.circular(5)),
      child: Column(
        children: [
          5.vGapDp,
          Row(
            children: [
              Text('商品金额', style: tsBlackBig),
              Spacer(),
              Text('¥${Config.formatMoney(orderInfoData.orderPrice)}',
                  style: tsBlack),
            ],
          ),
          5.vGapDp,
          1.gapV(Colors.grey[200]),
          5.vGapDp,
          Row(
            children: [
              Text('运费', style: tsBlackBig),
              Spacer(),
              Text('免费', style: tsBlack),
            ],
          ),
          5.vGapDp,
        ],
      ),
    );
  }
}
